package org.stephen.recommend.model;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import org.stephen.recommend.util.CommonUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: ViewedArticle
 * Description:
 * Date: 2020/12/16 14:25
 *
 * @author stephen.qiu
 */
public class ViewedArticles extends Model<ViewedArticles> {
    private static final long serialVersionUID = 1L;

    private HashMap<String, LocalDateTime> viewedArticleTimeMap;

    public ViewedArticles() {
        setViewedArticleTimeMap(new HashMap<>(CommonUtils.initHashMapSize(0)));
    }

    public HashMap<String, LocalDateTime> getViewedArticleTimeMap() {
        return viewedArticleTimeMap;
    }

    public void setViewedArticleTimeMap(HashMap<String, LocalDateTime> viewedArticleTimeMap) {
        this.viewedArticleTimeMap = viewedArticleTimeMap;
    }

    /**
     * 获取CFValidDay内浏览过的文章
     *
     * @param CFValidDay
     * @return
     */
    public List<String> getViewedArticlesList(int CFValidDay) {
        List<Map.Entry<String, LocalDateTime>> list = new ArrayList<>(viewedArticleTimeMap.entrySet());
        return list.stream().filter(c -> c.getValue().isAfter(LocalDateTime.now().plusDays(0 - CFValidDay))).map(c -> c.getKey()).collect(Collectors.toList());
    }

    /**
     * 移除previousDays 之外浏览过的文章
     *
     * @param previousDays
     */
    public void updateViewedArticles(int previousDays) {
        Iterator<Map.Entry<String, LocalDateTime>> iterator = viewedArticleTimeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, LocalDateTime> entry = iterator.next();
            if (entry.getValue().isBefore(LocalDateTime.now().plusDays(0 - previousDays))) {
                iterator.remove();
            }
        }
    }

    /**
     * 更新浏览列表
     *
     * @param articleId
     * @return
     */
    public void updateViewedArticles(String articleId) {
        viewedArticleTimeMap.put(articleId, LocalDateTime.now());
    }
}
